<template>
  <div v-if="visible" class="modal-overlay" @click="handleOverlayClick">
    <div class="zip-preview-modal" @click.stop>
      <!-- 模态框头部 -->
      <div class="modal-header">
        <h3 class="modal-title">压缩包内容预览</h3>
        <button class="close-btn" @click="handleClose">&times;</button>
      </div>

      <!-- 模态框内容 -->
      <div class="modal-body">
        <!-- 压缩包信息 -->
        <div class="zip-info">
          <div class="info-item">
            <span class="info-label">压缩包名称：</span>
            <span class="info-value">{{ zipFileName }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">总文件数：</span>
            <span class="info-value">{{ parseResult.totalFiles }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">模型文件：</span>
            <span class="info-value">{{ parseResult.modelFileCount }} 个</span>
          </div>
          <div class="info-item">
            <span class="info-label">其他文件：</span>
            <span class="info-value">{{ parseResult.otherFileCount }} 个</span>
          </div>
        </div>

        <!-- 文件列表 -->
        <div class="file-list-section">
          <div class="section-header">
            <h4 class="section-title">3D模型文件</h4>
            <div class="selection-controls">
              <button 
                class="btn-select-all" 
                @click="selectAll"
                :disabled="modelFiles.length === 0"
              >
                全选
              </button>
              <button 
                class="btn-select-none" 
                @click="selectNone"
                :disabled="modelFiles.length === 0"
              >
                全不选
              </button>
            </div>
          </div>

          <!-- 文件列表 -->
          <div class="file-list">
            <div 
              v-for="(file, index) in modelFiles" 
              :key="file.path"
              class="file-item"
              :class="{ 'selected': file.selected, 'expanded': expandedIndexes.includes(index) }"
            >
              <!-- 文件图标和基本信息 -->
              <div class="file-info" @click="toggleExpand(index)">
                <div class="file-details">
                  <div class="file-name">{{ file.name }}</div>
                  <div class="file-meta">
                    <span class="file-type">{{ file.type.toUpperCase() }}</span>
                    <span class="file-size">{{ formatFileSize(file.size) }}</span>
                  </div>
                </div>
                <div class="expand-icon" :class="{ 'open': expandedIndexes.includes(index) }">
                  ▼
                </div>
              </div>

              <!-- 选择控制 -->
              <div class="file-controls">
                <label class="checkbox-wrapper">
                  <input 
                    type="checkbox" 
                    v-model="file.selected"
                    class="file-checkbox"
                    @click.stop
                  >
                  <span class="checkbox-label">选择</span>
                </label>
              </div>

              <!-- 展开的表单区域 -->
              <div v-if="expandedIndexes.includes(index)" class="file-form" @click.stop>
                <!-- 产品名称 -->
                <div class="form-group-mini">
                  <label class="form-label-mini">产品名称</label>
                  <input 
                    type="text" 
                    v-model="file.productName"
                    :placeholder="`例如：${file.name.replace(/\.(glb|gltf)$/i, '')}`"
                    class="form-input-mini"
                    maxlength="50"
                  >
                </div>

                <!-- 分类选择 -->
                <div class="form-group-mini">
                  <label class="form-label-mini">分类</label>
                  <select v-model="file.category" class="form-select-mini">
                    <option value="">请选择分类</option>
                    <option v-for="category in props.categories" :key="category" :value="category">
                      {{ category }}
                    </option>
                  </select>
                </div>

                <!-- 描述 -->
                <div class="form-group-mini">
                  <label class="form-label-mini">描述（选填）</label>
                  <textarea 
                    v-model="file.description"
                    placeholder="请描述这个3D模型的特点、用途等..."
                    class="form-textarea-mini"
                    rows="2"
                    maxlength="200"
                  ></textarea>
                </div>

                <!-- 封面图片 -->
                <div class="form-group-mini">
                  <label class="form-label-mini">封面图片（选填）</label>
                  <div class="cover-upload-mini">
                    <input 
                      type="file" 
                      :id="`cover-input-${index}`" 
                      accept="image/*"
                      @change="(e) => handleCoverUpload(e, index)"
                      style="display: none"
                    >
                    <label :for="`cover-input-${index}`" class="cover-zone-mini">
                      <div v-if="!file.surfacePlot && !coverPreviewUrls[index]" class="cover-placeholder-mini">
                        <img :src="uploadIcon" alt="上传" class="upload-icon-mini" />
                        <p>点击上传封面</p>
                      </div>
                      <img v-else :src="coverPreviewUrls[index]" alt="封面预览" class="cover-preview-mini" />
                    </label>
                    <button v-if="file.surfacePlot || coverPreviewUrls[index]" 
                            class="btn-remove-cover"
                            @click="removeCover(index)"
                    >
                      移除
                    </button>
                  </div>
                </div>
                
                <!-- 是否压缩 -->
                <div class="form-group-mini">
                  <label class="form-label-mini">是否压缩文件</label>
                  <div style="display:flex; align-items:center; gap:8px;">
                    <input type="checkbox" :id="`ifDraco-${index}`" v-model="file.ifDraco" />
                    <label :for="`ifDraco-${index}`" style="font-size:12px; color:#666;">勾选则启用 Draco 压缩（默认勾选）</label>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 选择统计 -->
          <div class="selection-summary">
            <span class="summary-text">
              已选择 {{ selectedFiles.length }} / {{ modelFiles.length }} 个文件
            </span>
            <span class="summary-size">
              总大小：{{ formatFileSize(totalSelectedSize) }}
            </span>
          </div>
        </div>

        <!-- 错误信息 -->
        <div v-if="errorMessage" class="error-message">
          <div class="error-icon">⚠️</div>
          <div class="error-text">{{ errorMessage }}</div>
        </div>
      </div>

      <!-- 模态框底部 -->
      <div class="modal-footer">
        <button 
          class="btn-cancel" 
          @click="handleClose"
          :disabled="isUploading"
        >
          取消
        </button>
        <button 
          class="btn-primary" 
          @click="handleConfirm"
          :disabled="selectedFiles.length === 0 || isUploading"
        >
          {{ isUploading ? '上传中...' : `确认上传 ${selectedFiles.length} 个文件` }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { formatFileSize, getFileTypeIcon } from '@/utils/zipParser'
import uploadIcon from '@/assets/upload.svg'

// 组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  parseResult: {
    type: Object,
    required: true
  },
  zipFileName: {
    type: String,
    default: ''
  },
  isUploading: {
    type: Boolean,
    default: false
  },
  // 分类列表，从父组件传入
  categories: {
    type: Array,
    default: () => [
      '建筑模型',
      '家具模型',
      '交通工具',
      '角色模型',
      '衣物模型',
      '自然景观',
      '电子产品',
      '其他'
    ]
  }
})

// 组件事件
const emit = defineEmits(['close', 'confirm'])

// 响应式数据
const modelFiles = ref([])
const errorMessage = ref('')
const expandedIndexes = ref([])
const coverPreviewUrls = ref({})

/**
 * 计算属性：选中的文件
 */
const selectedFiles = computed(() => {
  return modelFiles.value.filter(file => file.selected)
})

/**
 * 计算属性：选中文件的总大小
 */
const totalSelectedSize = computed(() => {
  return selectedFiles.value.reduce((total, file) => total + file.size, 0)
})

const initializeModelFiles = () => {
  if (props.parseResult.success && props.parseResult.modelFiles.length > 0) {
    modelFiles.value = props.parseResult.modelFiles.map(file => ({
      ...file,
      selected: true,
      productName: '', // 初始化产品名称
      category: '', // 初始化分类
      description: '', // 初始化描述
  surfacePlot: null, // 初始化封面图片
  ifDraco: true // 默认需要压缩
    }))
    errorMessage.value = ''
  } else {
    modelFiles.value = []
    errorMessage.value = props.parseResult.error || '解析失败'
  }
  // 清空展开状态和封面预览
  expandedIndexes.value = []
  coverPreviewUrls.value = {}
}

//保证展开文件只有一个
const toggleExpand = (index) => {
  const idx = expandedIndexes.value.indexOf(index)
  if (idx > -1) {
    expandedIndexes.value.splice(idx, 1)
  } else {
    expandedIndexes.value = [index]
  }
}

const handleCoverUpload = (event, index) => {
  const target = event.target
  const file = target.files?.[0]
  if (!file) return
  
  const fileItem = modelFiles.value[index]
  if (!fileItem) return
  
  // 更新文件信息
  fileItem.surfacePlot = file
  
  // 创建预览 URL
  const url = URL.createObjectURL(file)
  coverPreviewUrls.value[index] = url
}

const removeCover = (index) => {
  // 释放旧的 URL
  if (coverPreviewUrls.value[index]) {
    URL.revokeObjectURL(coverPreviewUrls.value[index])
  }
  
  const fileItem = modelFiles.value[index]
  if (fileItem) {
    // 清除封面图片
    fileItem.surfacePlot = null
  }
  delete coverPreviewUrls.value[index]
}

const selectAll = () => {
  modelFiles.value.forEach(file => file.selected = true)
}

const selectNone = () => {
  modelFiles.value.forEach(file => file.selected = false)
}

const handleConfirm = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请至少选择一个文件进行上传')
    return
  }
  
  // 验证每个选中文件的必填字段
  for (const file of selectedFiles.value) {
    if (!file.productName || !file.productName.trim()) {
      ElMessage.error(`文件 "${file.name}" 缺少产品名称`)
      return
    }
    if (!file.category) {
      ElMessage.error(`文件 "${file.name}" 未选择分类`)
      return
    }
  }
  
  // 把每个文件的 ifDraco 和 surfacePlot 等信息一并传递给父组件
  const payload = selectedFiles.value.map(f => ({
    name: f.name,
    path: f.path,
    size: f.size,
    type: f.type,
    productName: f.productName,
    category: f.category,
    description: f.description,
    surfacePlot: f.surfacePlot || null,
    ifDraco: typeof f.ifDraco === 'boolean' ? f.ifDraco : true
  }))

  emit('confirm', payload)
}

const handleClose = () => {
  emit('close')
}

const handleOverlayClick = (event) => {
  if (event.target === event.currentTarget) {
    handleClose()
  }
}

watch(() => props.parseResult, () => {
  initializeModelFiles()
}, { immediate: true, deep: true })
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.zip-preview-modal {
  background: white;
  border-radius: 15px;
  width: 100%;
  max-width: 800px;
  max-height: 90vh;
  overflow: hidden;
  color: #333;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

/* 模态框头部 */
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 1px solid #eee;
  background: #f8f9fa;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  cursor: pointer;
  color: #999;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
  padding: 0;
  line-height: 1;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
  transform: scale(1.1);
}

/* 模态框内容 */
.modal-body {
  padding: 25px;
  max-height: 60vh;
  overflow-y: auto;
}

/* 压缩包信息 */
.zip-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #333;
  font-weight: 600;
}

/* 文件列表区域 */
.file-list-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.selection-controls {
  display: flex;
  gap: 10px;
}

.btn-select-all,
.btn-select-none {
  background: #3742fa;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-select-all:hover:not(:disabled),
.btn-select-none:hover:not(:disabled) {
  background: #2f3af2;
  transform: translateY(-1px);
}

.btn-select-all:disabled,
.btn-select-none:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 文件列表 */
.file-list {
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  overflow: hidden;
  max-height: 300px;
  overflow-y: auto;
}

.file-item {
  flex-direction: column;
  align-items: stretch;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.2s;
  background: white;
}

.file-item:last-child {
  border-bottom: none;
}

.file-item:hover {
  background: #f8f9ff;
}

.file-item.selected {
  background: #e8f2ff;
  border-left: 3px solid #3742fa;
}

.file-item.expanded {
  background: #f8f9fa;
}

/* 文件信息 */
.file-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.file-details {
  flex: 1;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
  word-break: break-all;
}

.file-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #666;
}

.file-type {
  background: #e8f2ff;
  color: #3742fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 500;
}

.file-size {
  color: #666;
}

/* 展开图标 */
.expand-icon {
  font-size: 12px;
  color: #666;
  transition: transform 0.3s;
  cursor: pointer;
}

.expand-icon.open {
  transform: rotate(180deg);
}

/* 文件控制 */
.file-controls {
  display: flex;
  align-items: center;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.file-checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.checkbox-label {
  font-size: 12px;
  color: #666;
  user-select: none;
}

/* 选择统计 */
.selection-summary {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 10px 15px;
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.summary-text {
  color: #333;
  font-weight: 500;
}

.summary-size {
  color: #666;
}

/* 错误信息 */
.error-message {
  background: #fff5f5;
  border: 1px solid #fed7d7;
  border-radius: 6px;
  padding: 12px 15px;
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 15px;
}

.error-icon {
  font-size: 16px;
}

.error-text {
  color: #e53e3e;
  font-size: 14px;
  font-weight: 500;
}

/* 模态框底部 */
.modal-footer {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  padding: 20px 25px;
  border-top: 1px solid #eee;
  background: #f8f9fa;
}

.btn-cancel {
  background: #6c757d;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-cancel:hover:not(:disabled) {
  background: #5a6268;
  transform: translateY(-1px);
}

.btn-cancel:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn-primary {
  background: #3742fa;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-primary:hover:not(:disabled) {
  background: #2f3af2;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(55, 66, 250, 0.3);
}

.btn-primary:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .zip-preview-modal {
    margin: 10px;
    max-height: 95vh;
  }
  
  .zip-info {
    grid-template-columns: 1fr;
  }
  
  .file-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .file-controls {
    align-self: flex-end;
  }
  
  .selection-summary {
    flex-direction: column;
    gap: 5px;
    text-align: center;
  }
}

/* 展开的文件表单 */
.file-form {
  margin-top: 15px;
  padding: 15px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e5e5e5;
}

.form-group-mini {
  margin-bottom: 15px;
}

.form-group-mini:last-child {
  margin-bottom: 0;
}

.form-label-mini {
  display: block;
  font-size: 12px;
  font-weight: 500;
  color: #666;
  margin-bottom: 6px;
}

.form-input-mini,
.form-select-mini,
.form-textarea-mini {
  width: 100%;
  padding: 8px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 13px;
  color: #333;
  background: white;
  transition: border-color 0.3s, box-shadow 0.3s;
  box-sizing: border-box;
}

.form-input-mini:focus,
.form-select-mini:focus,
.form-textarea-mini:focus {
  outline: none;
  border-color: #3742fa;
  box-shadow: 0 0 0 2px rgba(55, 66, 250, 0.1);
}

.form-textarea-mini {
  resize: vertical;
  min-height: 60px;
  font-family: inherit;
}

/* 封面图片上传 */
.cover-upload-mini {
  display: flex;
  gap: 10px;
  align-items: center;
}

.cover-zone-mini {
  display: block;
  width: 80px;
  height: 80px;
  border: 2px dashed #ddd;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
  background: #fafafa;
}

.cover-zone-mini:hover {
  border-color: #3742fa;
  background: #f8f9ff;
}

.cover-placeholder-mini {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 6px;
  color: #999;
}

.upload-icon-mini {
  width: 24px;
  height: 24px;
  opacity: 0.5;
}

.cover-placeholder-mini p {
  margin: 0;
  font-size: 11px;
}

.cover-preview-mini {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.btn-remove-cover {
  background: #ff4757;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-remove-cover:hover {
  background: #ff3838;
  transform: translateY(-1px);
}
</style>
